package com.ls.uav_backend.manger;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ls.uav_backend.exception.BusinessException;
import com.ls.uav_backend.exception.ErrorCode;
import com.ls.uav_backend.utils.OneNetSignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class OneNetResourceManger {

    @Value("${oneNet.access-key}")
    private String accessKey;

    @Value("${oneNet.product-id}")
    private String productId;

    @Value("${oneNet.device-name}")
    private String deviceName;

    public String getOneNetResource() {
        // 基础URL
        String baseUrl = "https://iot-api.heclouds.com/thingmodel/query-device-property";
        // 拼接查询字符串
        String query = "product_id=" + productId + "&device_name=" + deviceName;
        // 构建完整的URL
        String url = baseUrl + "?" + query;

        String version = "2022-05-01";
        String resourceName = "products/" + productId;
        String expirationTime = System.currentTimeMillis() / 1000 + 7 * 24 * 60 * 60 + "";
        String signatureMethod = "sha1";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            // 设置请求头
            String sign = OneNetSignUtil.assembleToken(version, resourceName, expirationTime, signatureMethod, accessKey);
            httpGet.setHeader("Accept", "application/json, text/plain, */*");
            httpGet.setHeader("authorization", sign);

            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (statusCode == 200 && entity != null) {
                String responseBody = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSONUtil.parseObj(responseBody);
                return jsonObject.getJSONArray("data").toString();
            }
        } catch (Exception e) {
            log.error("Error occurred while getting OneNet resource: {}", e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取OneNet资源失败");
        }
        return "";
    }
}
